package com.ham.mud.commands;

import com.ham.mud.ServerConnection;
import com.ham.mud.TargetableService;
import com.ham.mud.characters.player.Player;
import com.ham.mud.characters.player.PlayerService;
import com.ham.mud.items.Decoration;
import com.ham.mud.items.Item;
import com.ham.mud.rooms.Room;
import com.ham.mud.rooms.RoomService;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by hlucas on Jun 21, 2011 at 2:57:08 PM
 */
public class GetCommand extends PlayerCommand {
    @Override
    public void execute(ServerConnection connection, String[] params) {
        if(params.length == 0) {
            connection.printSolo("Get what?");
            return;
        }

        Player player = connection.getPlayer();
        int atX = player.getAtX();
        int atY = player.getAtY();

        Room room = RoomService.getRoom(player.getZone(), atX, atY);
        List<Item> items = room.getItems();
        
        String search = params[0];
        if(search.toLowerCase().equals("all")) {
            List<Item> all = new ArrayList<Item>();
            boolean isFirst = true;
            for (Item item : items) {
                if (item instanceof Decoration) continue;
                all.add(item);
                if(isFirst) {
                    connection.printSolo("You pick up " + item.getName() + ".");
                    isFirst = false;
                } else {
                    connection.printSolo("\nYou pick up " + item.getName() + ".");
                }
                room.printToOthers(player.getName() + " picks up " + item.getName(), connection);
            }

            for(Item item : all) {
                room.removeItem(item);
                player.addItem(item);
            }

            if(all.size() == 0) {
                connection.printSolo("You see nothing here to pick up.");
            }
            
            return;
        }

        Item item = (Item) TargetableService.findTarget(search, items);
        if(item == null) {
            connection.printSolo("You don't see that here.");
            return;
        }

        if(item instanceof Decoration) {
            connection.printSolo("You can't take that.");
            return;
        }

        room.removeItem(item);
        player.addItem(item);

        connection.printSolo("You pick up " + item.getName() + ".");
        room.printToOthers(player.getName() + " picks up " + item.getName(), connection);
        PlayerService.save(player);
    }

    @Override
    protected String getCommandName() {
        return "get";
    }
}
